<template>
  <el-scrollbar>
    <el-menu
      :default-active="activeMenu"
      :collapse="isCollapse"
      :unique-opened="true"
      :collapse-transition="false"
      mode="vertical"
      :background-color="menuBg"
      :text-color="menuText"
      :active-text-color="menuActiveText"
    >
      <sidebar-item
        v-for="route in routes"
        :key="route.path"
        :item="route"
        :base-path="route.path"
        :is-collapse="isCollapse"
      />
    </el-menu>
  </el-scrollbar>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import SidebarItem from './sidebar-item.vue'

defineOptions({
  name: 'MenuVertical'
})

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

const routes = computed(() => {
  // 允许显示所有路由，不再做路径过滤
  // 过滤出需要在菜单中显示的路由
  let filteredRoutes = router.options.routes.filter(route => {
    // 只显示有meta属性和标题的路由，且不是隐藏的
    // 如果路由需要特定角色，确保用户拥有这些角色
    const hasRequiredRoles = !route.meta?.roles || 
      route.meta.roles.some(role => userStore.roles.includes(role));
      
    return route.meta && 
           route.meta.title &&
           !route.hidden &&
           hasRequiredRoles;
  });
  
  // 手动排序，确保仪表盘在最前面
  filteredRoutes.sort((a, b) => {
    // 如果路径是 '/'，那么它应该排在最前面
    if (a.path === '/') return -1;
    if (b.path === '/') return 1;
    return 0;
  });
  
  return filteredRoutes;
})

const activeMenu = computed(() => {
  const { meta, path } = route
  // 如果设置了activeMenu属性，则使用activeMenu
  if (meta.activeMenu) {
    return meta.activeMenu
  }
  return path
})

const isCollapse = computed(() => !appStore.sidebar.opened)

// 菜单样式变量
const menuBg = computed(() => appStore.theme.menuBg || 'var(--menu-bg)')
const menuText = computed(() => appStore.theme.menuText || 'var(--menu-text)')
const menuActiveText = computed(() => appStore.theme.menuActiveText || 'var(--menu-active-text)')
</script>
